package cn.wolfcode.trip.base.util;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传工具
 */
public class UploadUtil {

    //存放图片的磁盘路径
    public static final String PATH = "c://trip";

    /**
     * 处理文件上传
     * @param file
     * @param basePath
     * @return 123.png
     */
    public static String upload(MultipartFile file, String basePath) {

        //获取随机生成的字符串
        String uuid = UUID.randomUUID().toString();

        String orgFileName = file.getOriginalFilename();
        String ext = "." + FilenameUtils.getExtension(orgFileName);
        String fileName = uuid + ext;
        try {
            File targetFile = new File(basePath, fileName);
            FileUtils.writeByteArrayToFile(targetFile, file.getBytes());

            return "/upload/" + fileName;

        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

}